package com.schoolhelper.controller;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.schoolhelper.constant.Api;
import com.schoolhelper.constant.Code;
import com.schoolhelper.constant.Message;
import com.schoolhelper.entity.TUser;
import com.schoolhelper.model.BaseRender;
import com.schoolhelper.model.DataRender;
import com.schoolhelper.model.MyToken;
import com.schoolhelper.model.Render;
import com.schoolhelper.service.TUserService;
import com.schoolhelper.service.impl.TUserServiceImpl;
import com.schoolhelper.vo.LoginVo;
import com.schoolhelper.vo.OrderDiscussVo;
import com.schoolhelper.vo.TokenVo;
import com.schoolhelper.vo.UserFollowerVo;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

/**
 * (TUser)表控制层
 *
 * @author makejava
 * @since 2021-04-23 21:03:36
 */
@RestController
@RequestMapping(Api.USER)
public class TUserController extends ApiController {
    /**
     * 服务对象
     */
    @Resource
    private TUserService tUserService;

    @SneakyThrows
    @PostMapping("/loginQuit")
    public String loginQuit(@RequestBody TokenVo tokenVo) {
        tUserService.loginQuit(tokenVo.getToken());

        BaseRender baseRender = new BaseRender(Code.SUCCESS, Message.LOGIN_QUIT_SUCCESS);
        return new ObjectMapper().writeValueAsString(baseRender);
    }

    @SneakyThrows
    @PostMapping("/getLoginState")
    public String getLoginState(@RequestBody TokenVo tokenVo) {
        String loginState = tUserService.getLoginState(tokenVo.getToken());
        System.out.println(loginState);
        if (loginState == null) {
            BaseRender baseRender = new BaseRender(Code.OVERDUE, Message.OVERDUE);
            return new ObjectMapper().writeValueAsString(baseRender);
        } else {
            Object loginStateObject = JSONObject.parse(loginState);
            DataRender dataRender = new DataRender(Code.SUCCESS, Message.LOGIN_STATE_VALID, loginStateObject);
            return new ObjectMapper().writeValueAsString(dataRender);

        }

    }

    @PostMapping("/getUserFollower")
    public List<UserFollowerVo> getUserFollower(@RequestBody TUser tUser) {
        Integer userId = tUser.getUserId();
        return tUserService.getUserFollower(userId);
    }

    @SneakyThrows
    @PostMapping("/login")
    public String login(@RequestBody LoginVo loginVo) {
        String phone = loginVo.getUsername();
        String password = loginVo.getPassword();
        System.out.println(phone);
        System.out.println(password);
        String token = tUserService.login(phone, password);

        if (token == null) {
            BaseRender baseRender = new BaseRender(Code.LOGIN_ERROR, Message.LOGIN_ERROR);
            return new ObjectMapper().writeValueAsString(baseRender);

        } else {
            DataRender dataRender = new DataRender(Code.LOGIN_SUCCESS, Message.LOGIN_SUCCESS, token);
            return new ObjectMapper().writeValueAsString(dataRender);

        }
    }

    @SneakyThrows
    @PostMapping("getByUsername")
    public String getByUserName(@RequestBody String requestBody) {
        JSONObject requestJson = (JSONObject) JSONObject.parse(requestBody);
        String username = (String) requestJson.get("username");
        System.out.println("根据username查询user：" + username);
        TUser byUsername = tUserService.getByUsername(username);
        if (byUsername == null) {
            BaseRender baseRender = new BaseRender(Code.SERVER_ERROR, Message.SEARCH_FAILED);
            return new ObjectMapper().writeValueAsString(baseRender);
        }
        return JSONObject.toJSONString(byUsername, SerializerFeature.WriteMapNullValue);
    }

    @SneakyThrows
    @PostMapping("getByPhone")
    public String getByPhone(@RequestBody String requestBody) {
        JSONObject requestJson = (JSONObject) JSONObject.parse(requestBody);
        String phone = (String) requestJson.get("phone");
        System.out.println("根据phone查询user：" + phone);
        TUser byPhone = tUserService.getByPhone(phone);
        if (byPhone == null) {
            BaseRender baseRender = new BaseRender(Code.SERVER_ERROR, Message.SEARCH_FAILED);
            return new ObjectMapper().writeValueAsString(baseRender);
        }
        return JSONObject.toJSONString(byPhone, SerializerFeature.WriteMapNullValue);
    }


    /**
     * 分页查询所有数据
     *
     * @param page  分页对象
     * @param tUser 查询实体
     * @return 所有数据
     */
    @GetMapping
    public R selectAll(Page<TUser> page, TUser tUser) {
        return success(this.tUserService.page(page, new QueryWrapper<>(tUser)));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{" + Api.ID + "}")
    public R selectOne(@PathVariable Serializable id) {
        return success(this.tUserService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param tUser 实体对象
     * @return 新增结果
     */
    @SneakyThrows
    @PostMapping
    public R insert(@RequestBody TUser tUser) {
        // 注册环信
        String phone = tUser.getPhone();
        String password = tUser.getPassword();
        System.out.println(phone);
        System.out.println(password);
        boolean hxResult = tUserService.registerInHx(phone, password);

        if (hxResult) {
            return success(this.tUserService.save(tUser));
        } else {
            return R.failed(Message.FAILED_MSG);
        }
    }

    /**
     * 修改数据
     *
     * @param tUser 实体对象
     * @return 修改结果
     */
    @PutMapping
    public R update(@RequestBody TUser tUser) {
        return success(this.tUserService.updateById(tUser));
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping
    public R delete(@RequestParam(Api.ID_LIST) List<Long> idList) {
        return success(this.tUserService.removeByIds(idList));
    }
}
